package com.koudai.finance.utils.wxpay;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @Description: 微信支付响应工具类
 * @Author: ls
 * @Date: 2020/08/10 14:05
 */
@Slf4j
public class ResponseUtils {

    /**
    * @Description:  响应
    * @Author: ls
    * @Date: 2020/08/10 14:07
    */
    public static void response(HttpServletResponse response, String responseMsg) {
        if (responseMsg == null) {
            return;
        }
        try {
            byte[] msgs = responseMsg.getBytes(StandardCharsets.UTF_8);
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentLength(msgs.length);
            response.getOutputStream().write(msgs);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("获取响应体异常:", e);
        }
    }

    /**
     * @Description: 获取请求体
     * @Author: ls
     * @Date: 2020/08/10 14:06
     */
    public static String getRequestBody(HttpServletRequest request) {
        String retText = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.ISO_8859_1));
            String tmp;
            StringBuilder htmlRet = new StringBuilder();
            while ((tmp = reader.readLine()) != null) {
                htmlRet.append(tmp).append("\n");
            }
            retText = new String(htmlRet.toString().trim().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("获取请求体异常:", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("获取请求体异常:", e);
                }
            }
        }
        return retText;
    }
}